import { Controller, Get, Post, Request, Response, Body } from '@nestjs/common'
import { validateToken, sign } from '../../utils/wechat'
import config from '../../config'

import { WechatService } from './wechat.service'

@Controller('wechat')
export class WechatController {
  constructor (
    private wechatService: WechatService
  ) {}

  @Get()
  getWechat ( @Request() req, @Response() res ) {
    return validateToken(req, res)
  }

  @Post('/user')
  async getUserInfo ( @Body() body ) {
    return await this.wechatService.getAccessTokenByCode(body.code)
  }

  @Post('/js_signature')
  async getSignature ( @Body() body ) {
    const jsapiObj = await this.wechatService.getJSAPITicketStraight()
    const timestamp = Math.floor((+new Date()) / 1000)
    const signature = sign(jsapiObj.ticket, body.url, config.wechat.nonceStr, timestamp)
    return { timestamp, signature, appId: config.wechat.appID, nonceStr: config.wechat.nonceStr }
  }
}
